from .models import User, Vip,Viptype,Comchistory
from rest_framework import serializers
import re
from redis import Redis


from django.core.cache import cache
from rest_framework.exceptions import ValidationError, APIException
from rest_framework_jwt.settings import api_settings

jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER


class LoginSerializer(serializers.ModelSerializer):
    username = serializers.CharField()

    class Meta:
        model = User
        fields = ['username', 'password']

    def _check_user(self, attrs):
        try:
            username = attrs.get('username')
            password = attrs.get('password')
            if re.match(r'0?(13|14|15|17|18)[0-9]{9}', username):
                user = User.objects.get(mobile=username)
            else:
                user = User.objects.get(username=username)
            if user.check_password(password):
                return user
            else:
                raise APIException(detail='密码错误')
        except APIException:
            raise APIException(detail='密码错误')
        except:
            raise APIException(detail='用户名不存在')

    def _get_token(self, user):
        payload = jwt_payload_handler(user)  # 根据当前登录用户获取荷载
        token = jwt_encode_handler(payload)  # 根据荷载生成token
        return token

    def validate(self, attrs):
        user = self._check_user(attrs)
        token = self._get_token(user)
        self.context['token'] = token
        self.context['username'] = user.username
        self.context['id']=user.id
        host = self.context.get('request').META.get('HTTP_HOST')
        self.context['icon'] = 'http://%s/media/%s' % (host, str(user.icon))
        return attrs


class SmsLoginSerializer(serializers.ModelSerializer):
    code = serializers.CharField()

    class Meta:
        model = User
        fields = ['mobile', 'code']

    def _check_user(self, attrs):
            mobile = attrs.get('mobile')
            code= attrs.get('code')
            old_code=cache.get('sms_cache_%s' % mobile)
            print(old_code)

            if old_code==code:
                user=User.objects.filter(mobile=mobile).first()
                if user:
                    cache.set('sms_cache_%s' % mobile, '')
                    return user
                else:
                    raise APIException(detail='用户不存在')
            else:
                raise APIException(detail='验证码错误')



    def _get_token(self, user):
        payload = jwt_payload_handler(user)
        token = jwt_encode_handler(payload)
        return token

    def validate(self, attrs):
        user = self._check_user(attrs)
        token = self._get_token(user)
        self.context['token'] = token
        conn = Redis(host="localhost",port=6379,)
        conn.lpush('gg', '欢迎用户%s回家' % user.username)
        conn.close()
        host = self.context.get('request').META.get('HTTP_HOST')
        self.context['username']=user.username
        self.context['icon'] = 'http://%s/media/%s' % (host, str(user.icon))
        return attrs


class UserSerializer(serializers.ModelSerializer):
    code = serializers.CharField(write_only=True)

    class Meta:
        model = User
        fields = ['mobile','password', 'code']
        extra_kwargs={'password': {'write_only': True}}


    def validate(self, attrs):
        mobile = attrs.get('mobile')
        code = attrs.get('code')
        old_code = cache.get('sms_cache_%s' % mobile)

        if not old_code == code:
            raise APIException(detail='验证码错误')
        if User.objects.filter(mobile=mobile).first():
            raise APIException(detail='该手机号已注册过了')
        attrs.pop('code')
        cache.set('sms_cache_%s' % mobile, '')
        conn = Redis(host="localhost", port=6379, )
        conn.lpush('gg','欢迎新用户%s来到本站'%'user_'+str(mobile)[0:4])
        conn.close()
        attrs['username'] = 'user_'+str(mobile)[0:4]
        return attrs
    def create(self, validated_data):
        user=User.objects.create_user(**validated_data)
        return user


class ModifySerializer(serializers.ModelSerializer):
    class Meta:
        model = User
        fields=['username','age','addr','gender','icon',]


class PasswordSerializer(serializers.ModelSerializer):
    class Meta:
        model = User
        fields=['password']

    def update(self, instance, validated_data):
        password=validated_data.get('password')
        new_password=self.context.get('request').data.get('new_password')
        if instance.check_password(password):
            instance.set_password(new_password)
            instance.save()
            return instance
        else:
            raise APIException(detail='原密码错误')

class VipSerializer(serializers.ModelSerializer):
    class Meta:
        model=Vip
        fields=['id','user','odd_time','expiration_time']
        estra_kwargs={"odd_time":{
            "read_only":True
        },
        "expiration_time":{
            "write_only":True
        }}



    def create(self, validated_data):
        type_day=self.context.get('request').data.get('type')
        price=Viptype.objects.get(vip_type=type_day).price
        token=self.context.get('request').data.get('token')
        # if(token==cache.get('token')):

class ComichistorySerizlizer(serializers.ModelSerializer):
    class Meta:
        model=Comchistory
        fields= ['users','comics']


